package cn.lanqiao.web.controller.business;

import java.beans.IntrospectionException;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.lanqiao.business.domain.vo.ExportRequest;
import cn.lanqiao.business.domain.vo.StudentTemplate;
import cn.lanqiao.business.utils.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.lanqiao.common.annotation.Log;
import cn.lanqiao.common.core.controller.BaseController;
import cn.lanqiao.common.core.domain.AjaxResult;
import cn.lanqiao.common.enums.BusinessType;
import cn.lanqiao.business.domain.Grades;
import cn.lanqiao.business.service.IGradesService;
import cn.lanqiao.common.utils.poi.ExcelUtil;
import cn.lanqiao.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 学生成绩信息Controller
 * 
 * @author lmx
 * @date 2024-07-08
 */
@RestController
@RequestMapping("/business/grades")
public class GradesController extends BaseController
{
    @Autowired
    private IGradesService gradesService;
    static String filePath;//doc模版
    static String filexlsPath;//xls模版

    static String outputUrl;//最终生成的模版位置

    private static final String ZIP_FILE_NAME = "export.zip";
    /**
     * 查询学生成绩信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:grades:list')")
    @GetMapping("/list")
    public TableDataInfo list(Grades grades)
    {
        startPage();
        List<Grades> list = gradesService.selectGradesList(grades);
        System.out.println(list);
        return getDataTable(list);
    }

    /**
     * 导出学生成绩信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:grades:export')")
    @Log(title = "学生成绩信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Grades grades)
    {
        List<Grades> list = gradesService.selectGradesList(grades);
        ExcelUtil<Grades> util = new ExcelUtil<Grades>(Grades.class);
        util.exportExcel(response, list, "学生成绩信息数据");
    }

    /**
     * 获取学生成绩信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:grades:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(gradesService.selectGradesById(id));
    }

    /**
     * 新增学生成绩信息
     */
    @PreAuthorize("@ss.hasPermi('business:grades:add')")
    @Log(title = "学生成绩信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Grades grades)
    {
        System.out.println(grades);
        //根据前端传过来的学生姓名查询该学生是否存在，如果不存在返回错误提示
        Integer i = gradesService.selectStuIdByStuName(grades.getStuName());
        if (i != null){
            //说明有数据
            grades.setStuId((long) i);
            return toAjax(gradesService.insertGrades(grades));
        }else {
            return error("该学生不存在");
        }
    }

    /**
     * 修改学生成绩信息
     */
    @PreAuthorize("@ss.hasPermi('business:grades:edit')")
    @Log(title = "学生成绩信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Grades grades)
    {
        System.out.println(grades);
        //根据前端传过来的学生姓名查询该学生是否存在，如果不存在返回错误提示
        Integer i = gradesService.selectStuIdByStuName(grades.getStuName());
        if (i != null){
            grades.setStuId((long) i);
            return toAjax(gradesService.updateGrades(grades));
        }else {
            return error("该学生不存在");
        }

    }

    /**
     * 删除学生成绩信息
     */
    @PreAuthorize("@ss.hasPermi('business:grades:remove')")
    @Log(title = "学生成绩信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(gradesService.deleteGradesByIds(ids));
    }
    /**
     * 下载学生成绩信息模版
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<Grades> util = new ExcelUtil<Grades>(Grades.class);
        util.importTemplateExcel(response, "学生成绩信息");
    }

    /**
     * 导入学生成绩信息
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @Log(title = "学生成绩信息", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('business:grades:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<Grades> util = new ExcelUtil<Grades>(Grades.class);
        List<Grades> gradesList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = gradesService.importUser(gradesList, updateSupport, operName);
        return success(message);
    }
    /**
     * 查询班级信息接口
     */
    @PreAuthorize("@ss.hasPermi('business:grades:query')")
    @GetMapping("/classList")
    public AjaxResult getclassList() {
        // return success(gradesService.selectGradesById(id));
        // List<Grades> grades = gradesService.selectClassList();
        return success(gradesService.selectClassList());
    }
    /**
     * 上传doc或者docx接口
     */
    @PreAuthorize("@ss.hasPermi('business:grades:import')")
    @PostMapping("/exportResults")
    public AjaxResult exportResults(MultipartFile file) throws IOException {
        // HttpServletResponse response
        System.out.println("现在进行Excel导出操作......");
        String uploadDir = "D:\\lanqiao_temporary\\directory\\"; // 指定上传文件的目录

        // 确保目录存在，如果不存在则创建
        File directory = new File(uploadDir);
        if (!directory.exists()){
            directory.mkdirs(); // 创建多级目录
        }

        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        filePath = uploadDir + originalFilename;
        System.out.println(filePath);
        try {
            // 保存文件到指定目录
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
            stream.write(bytes);
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return success("上传成功");
    }
    @PreAuthorize("@ss.hasPermi('business:grades:import')")
    @PostMapping("/exportStudentsResults")
    public AjaxResult exportResults(@RequestBody ExportRequest exportRequest, HttpServletResponse response) throws IOException, IntrospectionException, IllegalAccessException, InstantiationException {
        String className = exportRequest.getClassId();
        String coursesName = exportRequest.getCoursesId();
        String semesterName = exportRequest.getSemesterId();
        String deliveryIS = exportRequest.getDeliveryId();
        String teacherName = exportRequest.getTeacherId();
        String projectName = exportRequest.getProjectId();
        if (deliveryIS.equals("true")){
            // 导出班级学生成绩+学生成绩模版信息
            exportClassStudentProjectResult(className, coursesName, semesterName, teacherName, projectName,response);
            return success("上传成功");
        }else {
            //导出班级学生成绩成绩
            exportClassStudentResult(response, className, coursesName, semesterName);
            return success("上传成功");
        }
    }
    private void exportClassStudentProjectResult(String className, String coursesName, String semesterName, String teacherName, String projectName,HttpServletResponse response) throws IOException, IllegalAccessException, InstantiationException, IntrospectionException {
        //生成学生成绩信息
        //1.先生成Excel文件模版放入resources下 achievementTemplate
        //先根据用户的需求查询出相关的数据
        List<Grades> grades = gradesService.exportResults(className, semesterName, coursesName);
        //1.创建工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //2.创建工作表
        HSSFSheet sheet = workbook.createSheet("Sheet1");
        sheet.setDefaultColumnWidth(20);//设置所有列的列宽        //sheet上创建行
        int rownum = 0;
        HSSFRow row03 = sheet.createRow(rownum);
        String[] titles = {"stuName", "stuNum", "finalScore","priScore", "stuPerfce", "stuClass", "stuProjectName", "teacherName"};
        //得到表头的样式
        HSSFCellStyle tableTitleStyle = ExprotCellStyle.createTableTitleStyle(workbook);
        for (int i = 0; i < titles.length; i++) {
            HSSFCell cell = row03.createCell(i);
            cell.setCellValue(titles[i]);
            cell.setCellStyle(tableTitleStyle);
        }
        //表格主题样式
        HSSFCellStyle tableBodyStyle = ExprotCellStyle.setRowCellCenter(workbook);
        for (int i = 0; i < grades.size(); i++) {
            rownum++;
            HSSFRow row = sheet.createRow(rownum);
            Grades p = grades.get(i);
            //创建学生姓名
            HSSFCell stuNameCell = row.createCell(0);
            stuNameCell.setCellValue(p.getStuName());
            stuNameCell.setCellStyle(tableBodyStyle);
            // 创建学号单元格
            HSSFCell stuidCell = row.createCell(1);
            stuidCell.setCellValue("'" + p.getStudentID());
            // 创建一个数据格式对象
            HSSFDataFormat dataFormat = workbook.createDataFormat();
            // 创建一个单元格样式，并设置数据格式为文本
            HSSFCellStyle textCellStyle = workbook.createCellStyle();
            textCellStyle.setDataFormat(dataFormat.getFormat("@")); // "@" 表示文本格式
            // 将样式应用于学号单元格
            stuidCell.setCellStyle(textCellStyle);
            //创建期末成绩
            HSSFCell finalScoreCell = row.createCell(2);
            finalScoreCell.setCellValue(p.getProjectGrades());
            finalScoreCell.setCellStyle(tableBodyStyle);
            //创建平时成绩(40%)
            //todo:还差积分成绩20%
            HSSFCell usualGradesCell = row.createCell(3);
            if (p.getTotalUpScore() == null){
                usualGradesCell.setCellValue(NumberUtils.getNumFormat2((p.getExamScores()*0.2)+(p.getCourseGrades()*0.2)+(80 * 0.2)));
                usualGradesCell.setCellStyle(tableBodyStyle);
            }else if ((80+p.getTotalUpScore()) > 100){
                usualGradesCell.setCellValue(NumberUtils.getNumFormat2((p.getExamScores()*0.2)+(p.getCourseGrades()*0.2)+(100 * 0.2)));
                usualGradesCell.setCellStyle(tableBodyStyle);
            }else {
                usualGradesCell.setCellValue(NumberUtils.getNumFormat2((p.getExamScores()*0.2)+(p.getCourseGrades()*0.2)+((80+p.getTotalUpScore()) * 0.2)));
                usualGradesCell.setCellStyle(tableBodyStyle);
            }
            //创建专业
            HSSFCell stuPerfceCell = row.createCell(4);
            stuPerfceCell.setCellValue(p.getStuSpecialities());
            usualGradesCell.setCellStyle(tableBodyStyle);
            //创建班级
            HSSFCell stuClassCell = row.createCell(5);
            stuClassCell.setCellValue(p.getClaName());
            stuClassCell.setCellStyle(tableBodyStyle);
            //创建项目名
            HSSFCell projectCell = row.createCell(6);
            projectCell.setCellValue(projectName);
            projectCell.setCellStyle(tableBodyStyle);
            //创建老师名
            HSSFCell teacherCell = row.createCell(7);
            teacherCell.setCellValue(teacherName);
            teacherCell.setCellStyle(tableBodyStyle);
        }
        String fileName = className + coursesName +"模版表.xls";
        String uploadDir = "D:\\lanqiao_temporary\\template\\"; // 指定上传文件的目录
        // 确保目录存在，如果不存在则创建
        File directory = new File(uploadDir);
        if (!directory.exists()){
            directory.mkdirs(); // 创建多级目录
        }

        filexlsPath = uploadDir + fileName;
        // 将工作簿写入文件
        try (FileOutputStream fileOut = new FileOutputStream(filexlsPath)) {
            workbook.write(fileOut);
            System.out.println("Excel文件模版已成功导出");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            workbook.close();
        }
        //生成模版文件之后生成相关的学生成绩信息文档
        //1.doc或者docx模版文件路径
        String inputUrl = filePath;
        System.out.println("doc或者docx模版文件路径:"+inputUrl);
        //2.设定Excel文件模版所在路径
        String excelFileName = filexlsPath;
        System.out.println("设定Excel文件模版所在路径:"+excelFileName);
        List<StudentTemplate> students = EXLSReader.parseExcelToMapListToObjectList(excelFileName, "Sheet1", 1, StudentTemplate.class);
        students.forEach(student -> {
            // 需要替换的内容  heheTest替换成666    word模板中需要这样写${heheTest}
            // 替换学号中的单引号
            String cleanedStuNum = student.getStuNum().replace("'", "");
            Map<String, Object> testMap = new HashMap<>();
            testMap.put("stu_name", student.getStuName());
            testMap.put("stu_perfce", student.getStuPerfce());
            testMap.put("stu_class", student.getStuClass());
            testMap.put("stu_num", cleanedStuNum);

            testMap.put("finalScore", NumberUtils.getNumFormat2(student.getFinalScore()));
            //期末总成绩保留2位小数
            testMap.put("finalScoreP4",NumberUtils.getNumFormat2(student.getFinalScore()*0.4));
            //平时成绩需要没有小数点
            testMap.put("priScoreP6", NumberUtils.getNumFormat2(student.getPriScore()));
            double total = student.getFinalScore() * 0.4 + student.getPriScore();
            DecimalFormat decimalFormat = new DecimalFormat("#.##");
            testMap.put("total", decimalFormat.format(total));
            testMap.put("teacherName",student.getTeacherName());
            testMap.put("stu_project_name", student.getStuProjectName());
            int[] array = ArrayUtils.getArray((int)student.getFinalScore());

            for(int i=1;i<=array.length;i++){
                testMap.put("num"+i, array[i-1]);
            }
            //输出位置
            outputUrl = "C:\\"+className+"_"+coursesName+"\\"+student.getStuName()+"\\"+student.getStuName()+"-"+cleanedStuNum+".docx";
            ExportWordDocxUtil.changWord(inputUrl, outputUrl, testMap);
        });
        //先根据用户的需求查询出相关的数据
        List<Grades> grades1 = gradesService.exportResults(className, semesterName, coursesName);
        //1.创建工作簿
        HSSFWorkbook workbook1 = new HSSFWorkbook();
        //2.创建工作表
        HSSFSheet sheet1 = workbook1.createSheet(className + coursesName +"信息表");
        sheet1.setDefaultColumnWidth(20);//设置所有列的列宽
        //3.首行合并
        CellRangeAddress region1 = new CellRangeAddress(0, 0, 0,12);
        CellRangeAddress region2 = new CellRangeAddress(1, 1, 0, 12);
        sheet1.addMergedRegion(region1);
        sheet1.addMergedRegion(region2);
        //sheet上创建行
        int rownum1 = 0;
        HSSFRow row01 = sheet1.createRow(rownum1);
        //在row01上创建单元格
        HSSFCell cell_row01 = row01.createCell(0);
        //向cell_row01写东西
        cell_row01.setCellValue("学生成绩数据");
        //设置标题样式
        HSSFCellStyle titleStyle = ExprotCellStyle.createTitleCellStyle(workbook1);
        cell_row01.setCellStyle(titleStyle);
        //第二行
        rownum1++;
        HSSFRow row02 = sheet1.createRow(rownum1);
        HSSFCell cell_row02 = row02.createCell(0);
        cell_row02.setCellValue("总数:" + grades1.size() + "，导出时间:" + DateUtils.nowTime());
        //设置小标题样式
        HSSFCellStyle secondTitleStyle = ExprotCellStyle.createSecondTitleStyle(workbook1);
        cell_row02.setCellStyle(secondTitleStyle);
        //第三行
        rownum1++;
        HSSFRow row031 = sheet1.createRow(rownum1);
        String[] titless = {"学号", "姓名", "册考成绩","册考(20%)", "云课成绩", "云课成绩(20%)","积分成绩","积分成绩(20%)", "答辩成绩", "答辩成绩(40%)","平时成绩(40%)","总成绩"};
        //得到表头的样式
        HSSFCellStyle tableTitleStyle1 = ExprotCellStyle.createTableTitleStyle(workbook1);
        for (int i = 0; i < titless.length; i++) {
            HSSFCell cell = row031.createCell(i);
            cell.setCellValue(titless[i]);
            cell.setCellStyle(tableTitleStyle1);
        }
        //表格主题样式
        HSSFCellStyle tableBodyStyle1 = ExprotCellStyle.setRowCellCenter(workbook1);
        for (int i = 0; i < grades1.size(); i++) {
            rownum1++;

            HSSFRow row = sheet1.createRow(rownum1);
            Grades p = grades1.get(i);
            //创建学号
            HSSFCell stuidCell = row.createCell(0);
            stuidCell.setCellValue(p.getStudentID());
            stuidCell.setCellStyle(tableBodyStyle1);
            //创建姓名
            HSSFCell stuNameCell = row.createCell(1);
            stuNameCell.setCellValue(p.getStuName());
            stuNameCell.setCellStyle(tableBodyStyle1);
            //创建册考成绩
            HSSFCell examCell = row.createCell(2);
            examCell.setCellValue(p.getExamScores());
            examCell.setCellStyle(tableBodyStyle1);
            //创建册考成绩(20%)
            HSSFCell examCell1 = row.createCell(3);
            examCell1.setCellValue(NumberUtils.getNumFormat2(p.getExamScores()*0.2));
            examCell1.setCellStyle(tableBodyStyle1);
            //创建云课成绩
            HSSFCell courseCell = row.createCell(4);
            courseCell.setCellValue(NumberUtils.getNumFormat2(p.getCourseGrades()));
            courseCell.setCellStyle(tableBodyStyle1);
            //创建云课成绩(20%)
            HSSFCell courseCell1 = row.createCell(5);
            courseCell1.setCellValue(NumberUtils.getNumFormat2(p.getCourseGrades()*0.2));
            courseCell1.setCellStyle(tableBodyStyle1);
            //创建积分成绩
            HSSFCell integralCell1 = row.createCell(6);
            if (p.getTotalUpScore() == null){
                integralCell1.setCellValue(80);
                integralCell1.setCellStyle(tableBodyStyle1);
            }else if ((80+p.getTotalUpScore() >100)){
                integralCell1.setCellValue(100);
                integralCell1.setCellStyle(tableBodyStyle1);
            }else {
                integralCell1.setCellValue(80+p.getTotalUpScore());
                integralCell1.setCellStyle(tableBodyStyle1);
            }
            //创建积分成绩(20%)
            HSSFCell integralCell2 = row.createCell(7);
            if (p.getTotalUpScore() == null){
                integralCell2.setCellValue(NumberUtils.getNumFormat2(80*0.2));
                integralCell2.setCellStyle(tableBodyStyle1);
            }else if ((80+p.getTotalUpScore() >100)){
                integralCell2.setCellValue(NumberUtils.getNumFormat2(100*0.2));
                integralCell2.setCellStyle(tableBodyStyle1);
            }else {
                integralCell2.setCellValue(NumberUtils.getNumFormat2((80+p.getCourseGrades())*0.2));
                integralCell2.setCellStyle(tableBodyStyle1);
            }
            //创建期末成绩
            HSSFCell projectCell = row.createCell(8);
            projectCell.setCellValue(p.getProjectGrades());
            projectCell.setCellStyle(tableBodyStyle1);
            //创建期末成绩(40%)
            HSSFCell projectCell1 = row.createCell(9);
            projectCell1.setCellValue(p.getProjectGrades()*0.4);
            projectCell1.setCellStyle(tableBodyStyle1);
            //创建平时成绩(40%)
            //todo:还差积分成绩20%
            HSSFCell usualGradesCell = row.createCell(10);
            if (p.getTotalUpScore() == null){
                usualGradesCell.setCellValue(NumberUtils.getNumFormat2((p.getExamScores()*0.2)+(p.getCourseGrades()*0.2)+(80)*0.2));
                usualGradesCell.setCellStyle(tableBodyStyle1);
            }else if (p.getTotalUpScore() > 100){
                usualGradesCell.setCellValue(NumberUtils.getNumFormat2((p.getExamScores()*0.2)+(p.getCourseGrades()*0.2)+(100)*0.2));
                usualGradesCell.setCellStyle(tableBodyStyle1);
            }else {
                usualGradesCell.setCellValue(NumberUtils.getNumFormat2((p.getExamScores()*0.2)+(p.getCourseGrades()*0.2)+(80+p.getTotalUpScore())*0.2));
                usualGradesCell.setCellStyle(tableBodyStyle1);
            }

            //创建总成绩
            HSSFCell AllCell = row.createCell(11);
            if (p.getTotalUpScore() == null){
                AllCell.setCellValue(NumberUtils.getNumFormat2((p.getProjectGrades()*0.4)+(p.getCourseGrades()*0.2)+(p.getExamScores()*0.2)+(80)*0.2));
                AllCell.setCellStyle(tableBodyStyle1);
            }else if ((80+p.getTotalUpScore() > 100)){
                AllCell.setCellValue(NumberUtils.getNumFormat2((p.getProjectGrades()*0.4)+(p.getCourseGrades()*0.2)+(p.getExamScores()*0.2)+(100)*0.2));
                AllCell.setCellStyle(tableBodyStyle1);
            }else {
                AllCell.setCellValue(NumberUtils.getNumFormat2((p.getProjectGrades()*0.4)+(p.getCourseGrades()*0.2)+(p.getExamScores()*0.2)+(80+p.getCourseGrades())*0.2));
                AllCell.setCellStyle(tableBodyStyle1);
            }
        }
        //3.设置content-disposition响应头控制浏览器以下载的形式打开文件
        //下载中文文件时，需要注意的地方就是中文文件名要使用
        // String fileName1 = "D:\\"+className+"_"+coursesName+"\\"+className + "-" + coursesName + "成绩表.xls";
        // 拼接文件路径
        String fileName1 = "C:\\\\" + className + "_" + coursesName + "\\\\" + className + "-" + coursesName + "成绩表.xls";
        File file = new File(fileName1);
        File parentDir = file.getParentFile();

        // 创建父目录（如果不存在）
        if (!parentDir.exists()) {
            if (parentDir.mkdirs()) {
                System.out.println("父目录创建成功：" + parentDir);
            } else {
                System.err.println("父目录创建失败：" + parentDir);
                return;
            }
        }
        // 将工作簿写入文件
        try (FileOutputStream fileOut = new FileOutputStream(fileName1)) {
            workbook1.write(fileOut);
            System.out.println("Excel文件已成功导出");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            workbook1.close();
        }
        //生成成绩表放入ZIP包中
        String sourceDir = "C:\\\\"+className+"_"+coursesName; // 源文件夹路径
        // String zipFile = "C:\\\\Users\\\\zipfile.zip"; // 输出的 ZIP 文件路径
        String tempDir = System.getProperty("java.io.tmpdir");
        String zipFile = tempDir + File.separator + "zipfile.zip";
        compressFolder(sourceDir, zipFile);//将文件夹转换成ZIP文件
        // 设置HTTP响应头
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(className + "-" + coursesName + "成绩表.zip", "UTF-8"));
        response.setContentType("application/zip");

        // 读取ZIP文件
        try (FileInputStream fis = new FileInputStream(zipFile);
             OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
            os.flush();
        }

        System.out.println("数据导出完毕");
        //导出完毕之后删除临时目录
        //删除临时文件夹
        deleteDirectoryRecursively("C:\\\\"+className+"_"+coursesName);
        deleteDirectoryRecursively("C:\\\\lanqiao_temporary");
        deleteZipFile(zipFile);
        System.out.println("临时目录删除完毕");

    }

    private void exportClassStudentResult(HttpServletResponse response, String className, String coursesName, String semesterName) throws IOException {
        //先根据用户的需求查询出相关的数据
        List<Grades> grades = gradesService.exportResults(className, semesterName, coursesName);
        // 创建一个 ByteArrayOutputStream 用于存储 Excel 文件
        ByteArrayOutputStream excelStream = new ByteArrayOutputStream();
        //1.创建工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //2.创建工作表
        HSSFSheet sheet = workbook.createSheet(className + coursesName +"信息表");
        sheet.setDefaultColumnWidth(20);//设置所有列的列宽
        //3.首行合并
        CellRangeAddress region1 = new CellRangeAddress(0, 0, 0,12);
        CellRangeAddress region2 = new CellRangeAddress(1, 1, 0, 12);
        sheet.addMergedRegion(region1);
        sheet.addMergedRegion(region2);
        //sheet上创建行
        int rownum = 0;
        HSSFRow row01 = sheet.createRow(rownum);
        //在row01上创建单元格
        HSSFCell cell_row01 = row01.createCell(0);
        //向cell_row01写东西
        cell_row01.setCellValue("学生成绩数据");
        //设置标题样式
        HSSFCellStyle titleStyle = ExprotCellStyle.createTitleCellStyle(workbook);
        cell_row01.setCellStyle(titleStyle);
        //第二行
        rownum++;
        HSSFRow row02 = sheet.createRow(rownum);
        HSSFCell cell_row02 = row02.createCell(0);
        cell_row02.setCellValue("总数:" + grades.size() + "，导出时间:" + DateUtils.nowTime());
        //设置小标题样式
        HSSFCellStyle secondTitleStyle = ExprotCellStyle.createSecondTitleStyle(workbook);
        cell_row02.setCellStyle(secondTitleStyle);
        //第三行
        rownum++;
        HSSFRow row03 = sheet.createRow(rownum);
        String[] titles = {"学号", "姓名", "册考成绩","册考(20%)", "云课成绩", "云课成绩(20%)","积分成绩","积分成绩(20%)", "答辩成绩", "答辩成绩(40%)","平时成绩(40%)","总成绩"};
        //得到表头的样式
        HSSFCellStyle tableTitleStyle = ExprotCellStyle.createTableTitleStyle(workbook);
        for (int i = 0; i < titles.length; i++) {
            HSSFCell cell = row03.createCell(i);
            cell.setCellValue(titles[i]);
            cell.setCellStyle(tableTitleStyle);
        }
        //表格主题样式
        HSSFCellStyle tableBodyStyle = ExprotCellStyle.setRowCellCenter(workbook);
        for (int i = 0; i < grades.size(); i++) {
            rownum++;

            HSSFRow row = sheet.createRow(rownum);
            Grades p = grades.get(i);
            //创建学号
            HSSFCell stuidCell = row.createCell(0);
            stuidCell.setCellValue(p.getStudentID());
            stuidCell.setCellStyle(tableBodyStyle);
            //创建姓名
            HSSFCell stuNameCell = row.createCell(1);
            stuNameCell.setCellValue(p.getStuName());
            stuNameCell.setCellStyle(tableBodyStyle);
            //创建册考成绩
            HSSFCell examCell = row.createCell(2);
            examCell.setCellValue(p.getExamScores());
            examCell.setCellStyle(tableBodyStyle);
            //创建册考成绩(20%)
            HSSFCell examCell1 = row.createCell(3);
            examCell1.setCellValue(NumberUtils.getNumFormat2(p.getExamScores()*0.2));
            examCell1.setCellStyle(tableBodyStyle);
            //创建云课成绩
            HSSFCell courseCell = row.createCell(4);
            courseCell.setCellValue(NumberUtils.getNumFormat2(p.getCourseGrades()));
            courseCell.setCellStyle(tableBodyStyle);
            //创建云课成绩(20%)
            HSSFCell courseCell1 = row.createCell(5);
            courseCell1.setCellValue(NumberUtils.getNumFormat2(p.getCourseGrades()*0.2));
            courseCell1.setCellStyle(tableBodyStyle);
            //创建积分成绩
            HSSFCell integralCell = row.createCell(6);
            if (p.getTotalUpScore() == null){
                integralCell.setCellValue(80);
                integralCell.setCellStyle(tableBodyStyle);
            }else if ((80+p.getTotalUpScore() >100)){
                integralCell.setCellValue(100);
                integralCell.setCellStyle(tableBodyStyle);
            }else {
                integralCell.setCellValue(80+p.getTotalUpScore());
                integralCell.setCellStyle(tableBodyStyle);
            }
            //创建积分成绩(20%)
            HSSFCell integralCell1 = row.createCell(7);
            if (p.getTotalUpScore() == null){
                integralCell1.setCellValue(NumberUtils.getNumFormat2(80*0.2));
                integralCell1.setCellStyle(tableBodyStyle);
            }else if ((80+p.getTotalUpScore() >100)){
                integralCell1.setCellValue(NumberUtils.getNumFormat2(100*0.2));
                integralCell1.setCellStyle(tableBodyStyle);
            }else {
                integralCell1.setCellValue(NumberUtils.getNumFormat2((80+p.getCourseGrades())*0.2));
                integralCell1.setCellStyle(tableBodyStyle);
            }
            //创建期末成绩
            HSSFCell projectCell = row.createCell(8);
            projectCell.setCellValue(p.getProjectGrades());
            projectCell.setCellStyle(tableBodyStyle);
            //创建期末成绩(40%)
            HSSFCell projectCell1 = row.createCell(9);
            projectCell1.setCellValue(p.getProjectGrades()*0.4);
            projectCell1.setCellStyle(tableBodyStyle);
            //创建平时成绩(40%)
            //todo:还差积分成绩20%
            HSSFCell usualGradesCell = row.createCell(10);
            if (p.getTotalUpScore() == null){
                usualGradesCell.setCellValue(NumberUtils.getNumFormat2((p.getExamScores()*0.2)+(p.getCourseGrades()*0.2)+(80)*0.2));
                usualGradesCell.setCellStyle(tableBodyStyle);
            }else if (p.getTotalUpScore() > 100){
                usualGradesCell.setCellValue(NumberUtils.getNumFormat2((p.getExamScores()*0.2)+(p.getCourseGrades()*0.2)+(100)*0.2));
                usualGradesCell.setCellStyle(tableBodyStyle);
            }else {
                usualGradesCell.setCellValue(NumberUtils.getNumFormat2((p.getExamScores()*0.2)+(p.getCourseGrades()*0.2)+(80+p.getTotalUpScore())*0.2));
                usualGradesCell.setCellStyle(tableBodyStyle);
            }

            //创建总成绩
            HSSFCell AllCell = row.createCell(11);
            if (p.getTotalUpScore() == null){
                AllCell.setCellValue(NumberUtils.getNumFormat2((p.getProjectGrades()*0.4)+(p.getCourseGrades()*0.2)+(p.getExamScores()*0.2)+(80)*0.2));
                AllCell.setCellStyle(tableBodyStyle);
            }else if ((80+p.getTotalUpScore() > 100)){
                AllCell.setCellValue(NumberUtils.getNumFormat2((p.getProjectGrades()*0.4)+(p.getCourseGrades()*0.2)+(p.getExamScores()*0.2)+(100)*0.2));
                AllCell.setCellStyle(tableBodyStyle);
            }else {
                AllCell.setCellValue(NumberUtils.getNumFormat2((p.getProjectGrades()*0.4)+(p.getCourseGrades()*0.2)+(p.getExamScores()*0.2)+(80+p.getCourseGrades())*0.2));
                AllCell.setCellStyle(tableBodyStyle);
            }
        }
        // //3.设置content-disposition响应头控制浏览器以下载的形式打开文件
        // //下载中文文件时，需要注意的地方就是中文文件名要使用
        // String fileName = className+"-"+coursesName+"成绩表.xls";
        // // URLEncoder.encode方法进行编码(URLEncoder.encode(fileName, "字符编码"))，否则会出现文件名乱码。
        // response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        //
        // //输出字节流生成的Excel文件作为浏览器的一个输出流--进行输出
        // ServletOutputStream outputStream = response.getOutputStream();
        // //把Workbook作为浏览响应字节流进行附件下载
        // workbook.write(outputStream);
        // System.out.println("数据导出完毕");
        // //关闭流
        // outputStream.close();

        // 将 Excel 文件写入 ByteArrayOutputStream
        workbook.write(excelStream);
        workbook.close();
        // 创建一个 ByteArrayOutputStream 用于存储 Zip 文件
        ByteArrayOutputStream zipStream = new ByteArrayOutputStream();
        // 使用 ByteArrayOutputStream 创建 Zip 文件
        try (ZipOutputStream zos = new ZipOutputStream(zipStream)) {
            // 创建一个 ZipEntry 对象
            ZipEntry entry = new ZipEntry(className + "-" + coursesName + "成绩表.xls");

            // 将 Excel 文件的内容添加到 Zip 文件中
            zos.putNextEntry(entry);
            zos.write(excelStream.toByteArray());
            zos.closeEntry();
        }
        // 设置 HTTP 响应头以便用户可以下载 Zip 文件
        String fileName = className + "-" + coursesName + "成绩表.zip";
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("application/zip");

        // 输出 Zip 文件内容到 HttpServletResponse
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            outputStream.write(zipStream.toByteArray());
            outputStream.flush();
        }

        System.out.println("数据导出完毕");
    }
    private static void compressFolder(String sourceDir, String zipFile) {
        try (FileOutputStream fos = new FileOutputStream(zipFile);
             ZipOutputStream zos = new ZipOutputStream(fos)) {

            File fileToZip = new File(sourceDir);
            zipFile(fileToZip, fileToZip.getName(), zos);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void zipFile(File fileToZip, String fileName, ZipOutputStream zos) throws IOException {
        if (fileToZip.isHidden()) {
            return;
        }
        if (fileToZip.isDirectory()) {
            if (fileName.endsWith("/")) {
                zos.putNextEntry(new ZipEntry(fileName));
                zos.closeEntry();
            } else {
                zos.putNextEntry(new ZipEntry(fileName + "/"));
                zos.closeEntry();
            }
            File[] children = fileToZip.listFiles();
            for (File childFile : children) {
                zipFile(childFile, fileName + "/" + childFile.getName(), zos);
            }
            return;
        }

        try (FileInputStream fis = new FileInputStream(fileToZip)) {
            ZipEntry zipEntry = new ZipEntry(fileName);
            zos.putNextEntry(zipEntry);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zos.write(bytes, 0, length);
            }
            zos.closeEntry();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 递归删除文件夹及其内容。
     *
     * @param directoryPath 文件夹的路径
     * @throws IOException 如果删除过程中发生错误
     */
    public static void deleteDirectoryRecursively(String directoryPath) throws IOException {
        Path directory = Paths.get(directoryPath);
        Files.walk(directory)
                .sorted(Comparator.reverseOrder())
                .map(Path::toFile)
                .forEach(File::delete);
    }
    /**
     * 删除ZIP文件。
     *
     * @param zipFilePath ZIP文件的路径
     * @throws IOException 如果删除过程中发生错误
     */
    public static void deleteZipFile(String zipFilePath) throws IOException {
        Path zipFile = Paths.get(zipFilePath);
        Files.deleteIfExists(zipFile);
    }
}
